#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using BitwiseOre.Properties;
using BitwiseOre.SharedMemory.Core;
using BitwiseOre.SharedMemory.JetBrains;

namespace BitwiseOre.SharedMemory.Context
{
    [UsedImplicitly]
    internal sealed class ListenerConfig : ISemaphoreConfig, IMemoryMappedFileConfig, IListenerQueueConfig,
                                           ISharedObjectConfig, IEventWaitHandleConfig
    {
        private static readonly string MaxPendingConnectionsToLargeMessage = 
            Resources.ListenerConfig_MaxPendingConnectionsToLargeMessage;
        
        private readonly string _name;
        private readonly int _count;
        private readonly IGuidQueueSizer _sizer;

        public ListenerConfig(string name, IListenerContext properties, IGuidQueueSizer sizer)
        {
            if (sizer.IsCountTooLarge(properties.MaxPendingConnections))
            {
                throw new ArgumentOutOfRangeException("properties", properties.MaxPendingConnections,
                                                      MaxPendingConnectionsToLargeMessage);
            }
            _name = name;
            _count = properties.MaxPendingConnections;
            _sizer = sizer;
        }

        string ISemaphoreConfig.GetName()
        {
            return string.Format("{0}_sem", _name);
        }

        string IMemoryMappedFileConfig.Name
        {
            get { return string.Format("{0}_mem", _name); }
        }

        long IMemoryMappedFileConfig.Capacity
        { 
            get { return _sizer.Size(_count); }
        }

        int IListenerQueueConfig.Count
        {
            get { return _count; }
        }

        SharedObjectStatus ISharedObjectConfig.Status
        {
            get { return SharedObjectStatus.CreateNew; }
        }

        SharedObjectStatus IEventWaitHandleConfig.Status
        {
            get { return SharedObjectStatus.OpenExisting; }
        }
    }
}